package com.hankol.community

import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.BaseConstant
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.ARouterUtils
import com.baselibrary.utils.DoubleClickHelper
import com.baselibrary.utils.EventBusUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.hankol.community.adapter.TopicGoodUserAdapter
import com.hankol.community.databinding.ActivityTopicGoodUserBinding
import com.hankol.community.viewmodel.CommunityViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


/**
 *@author:hanke
 *2022/4/6
 *desc:活跃用户列表页
 */
@Route(path = ActivityRouter.COMMUNITY.COMMUNITY_TOPIC_GOOD_USER)
class TopicGoodUserActivity : BaseActivity() {
    private lateinit var mViewModel: CommunityViewModel
    private lateinit var mDataBinding: ActivityTopicGoodUserBinding
    val mAdapter: TopicGoodUserAdapter by lazy { TopicGoodUserAdapter() }
    private var mCurrentPage = 1
    private var mCurrentCursor = "0"
    private var mIsLoadingMore = false
    private var mNoMoreData = false
    private var selectedPosition = 0
    private var topicId = ""
    private var topicName = ""
    override fun getLayoutId(): Int {
        return R.layout.activity_topic_good_user
    }

    override fun init() {
        initView()
        requestData()
        addObserver()
    }

    private fun initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        topicId = ARouterUtils.parseParams(intent.extras!!, "tid")[0]
        topicName = ARouterUtils.parseParams(intent.extras!!, "tName")[0]
        if (intent.extras!!.containsKey("tid")) {
            topicId = intent.extras!!.getInt("tid").toString()
            topicName = intent.extras!!.getInt("tName").toString()
        }
        mDataBinding = getDataBinding<ActivityTopicGoodUserBinding>()
        mViewModel = getActivityViewModelProvider(this).get(CommunityViewModel::class.java)

        mDataBinding.tvTopicContentTop.text = "# $topicName"
        mDataBinding.rvTopicGoodUser.adapter = mAdapter
        mDataBinding.rlTopicGoodUser.setOnRefreshListener { _ -> refreshData() }
        mDataBinding.rlTopicGoodUser.setOnLoadMoreListener { _ ->
            if (mIsLoadingMore) {
                return@setOnLoadMoreListener
            }
            mCurrentPage++
            requestData()
        }
        mAdapter.onItemChildClickListener = BaseQuickAdapter.OnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tv_good_user_focus -> doFollowOrNot(position)
                R.id.civ_user_avatar -> goUserHomepage(position)
            }
        }

        mDataBinding.ivTopicGoodUserBack.setOnClickListener { finish() }
    }

    private fun doFollowOrNot(position: Int) {
        if (!DoubleClickHelper.isOnDoubleClick()) {
            selectedPosition = position
            mViewModel.reqFollow(this, !mAdapter.data[position].focusFans, 1, mAdapter.data[position].id)
        }
    }

    private fun goUserHomepage(position: Int) {
        if (!DoubleClickHelper.isOnDoubleClick()) {
            val hashMap = HashMap<String, Any>()
            hashMap[BaseConstant.USER_ID] = mAdapter.data[position].id.toString()
            ARouterUtils.jump(ActivityRouter.MINE_CENTER.USER_INFO, hashMap)
        }
    }

    private fun refreshData() {
        mNoMoreData = false
        mCurrentPage = 1
        requestData()
    }

    private fun addObserver() {
        mViewModel.followLiveData.observe(this, Observer {
            if (it.flag) {
                mAdapter.data[selectedPosition].focusFans = !mAdapter.data[selectedPosition].focusFans
                mAdapter.notifyItemChanged(selectedPosition)
                EventBusUtils.sendNotify1Value(MessageBus.msgId_follow_and_cancel, 0)
            }
        })

        mViewModel.goodUserLD.observe(this, Observer {
            mDataBinding.rlTopicGoodUser.finishRefresh()
            if (it?.data != null) {
                mCurrentCursor = it.nextCursor
                if (mCurrentPage == 1) {
                    if (it.data.isEmpty()) {
                        mAdapter.setEmptyView(com.baselibrary.R.layout.layout_common_empty_view, mDataBinding.rlTopicGoodUser)
                    } else {
                        mAdapter.setNewData(it.data)
                    }
                } else {
                    mDataBinding.rlTopicGoodUser.finishLoadMore(1)
                    mIsLoadingMore = false
                    if (mAdapter != null) {
                        mAdapter.addData(it.data)
                    }
                }
                if (mCurrentPage * 10 >= it.totalCount) {
                    mNoMoreData = true
                    mDataBinding.rlTopicGoodUser.finishLoadMoreWithNoMoreData()
                }
            } else {
                mNoMoreData = true
                mDataBinding.rlTopicGoodUser.finishLoadMoreWithNoMoreData()
            }
        })
    }

    private fun requestData() {
        if (!mNoMoreData) {
            mViewModel.requestTopicGoodUser(mCurrentPage, topicId)
        }
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_follow_and_cancel) {
            val uid = messageBus.param1
            for ((index, data) in mAdapter.data.withIndex()) {
                if (data.id == uid) {
                    data.focusFans = true
                    mAdapter.notifyItemChanged(index)
                    break
                }
            }
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}